<template>
  <view class="page">
    <scroll-view class="list" scroll-y>
      <view class="item" v-for="(m, i) in items" :key="m.id">
        <image class="cover" :src="m.cover" mode="aspectFill" />
        <view class="meta">
          <text class="title">{{ m.title }}</text>
          <text class="artist">{{ m.artist }}</text>
        </view>
        <button class="unfav" @click="remove(m.id)">
          <uni-icons type="heart-filled" size="16" color="#ff4d4f"></uni-icons>
          <text class="unfav-text">取消</text>
        </button>
      </view>
      <view class="empty" v-if="!items.length">暂无收藏</view>
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const API_BASE_URL = 'http://localhost:3001'
const userId = ref('0')
const items = ref<any[]>([])

const fetchList = async () => {
  try {
    const res = await uni.request({ url: `${API_BASE_URL}/api/users/${userId.value}/favorites`, method: 'GET' })
    const data = res?.data as any
    items.value = Array.isArray(data?.items) ? data.items : []
  } catch {
    items.value = []
  }
}

const remove = async (musicId: number) => {
  try {
    await uni.request({ url: `${API_BASE_URL}/api/users/${userId.value}/favorites/${musicId}`, method: 'DELETE' })
    items.value = items.value.filter(x => x.id !== musicId)
    uni.showToast({ title: '已取消', icon: 'success' })
  } catch {
    uni.showToast({ title: '操作失败', icon: 'none' })
  }
}

onLoad((query) => {
  const localUser = uni.getStorageSync('user')
  if (!localUser?.id) {
    return uni.redirectTo({ url: '/pages/auth/login' })
  }
  userId.value = String(query?.userId || localUser.id)
  fetchList()
})
</script>

<style>
.page { min-height: 100vh; background: #f7f8fa; }
.list { height: 100vh; }
.item { display: flex; align-items: center; padding: 20rpx 24rpx; background: #fff; border-bottom: 1rpx solid #eee; }
.cover { width: 100rpx; height: 100rpx; border-radius: 10rpx; margin-right: 16rpx; }
.meta { flex: 1; display: flex; flex-direction: column; }
.title { font-size: 28rpx; color: #333; margin-bottom: 6rpx; }
.artist { font-size: 24rpx; color: #999; }
.unfav { 
  background: linear-gradient(135deg, #ff6b6b, #ff8e8e); 
  color: #fff; 
  border: none; 
  border-radius: 20rpx; 
  height: 64rpx; 
  padding: 0 20rpx; 
  display: flex;
  align-items: center;
  gap: 8rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);
  transition: all 0.3s ease;
}

.unfav:active {
  transform: scale(0.95);
  box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.4);
}

.unfav-text {
  font-size: 24rpx;
  font-weight: 500;
}
.empty { text-align: center; color: #999; padding: 60rpx 0; }
</style>



